package com.bba.manager.sku.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bba.manager.common.model.sku.Car;
import com.bba.manager.common.model.sku.DTO.carDTO;
import com.bba.manager.common.model.sku.Series;
import com.bba.manager.common.model.sku.VO.queryCar;
import com.bba.manager.sku.mapper.CarMapper;
import com.bba.manager.sku.service.IBrandService;
import com.bba.manager.sku.service.ICarService;
import com.bba.manager.sku.service.ISeriesService;
import com.bba.manager.sku.service.IStoreService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
public class StoreServiceImpl implements IStoreService {
    @Autowired
    private IBrandService brandService;
    @Autowired
    private ISeriesService seriesService;
    @Autowired
    private ICarService carService;
    @Autowired
    private CarMapper carMapper;
    /**
     * todo 查询所有车型
     * 1.如果车辆编号不为空，按车俩编号进行查询
     * 2.如果车系不为空按车系查询
     * 3.如果品牌不为空按品牌查询
     * 4.如果都为空查询所有的车
     * 5.转换成DTO返回
     */


    //将对应型号的车系分别封装好
    @Override
    public IPage getCarList(queryCar querycar) {
        Page<Car> page = new Page<>(querycar.getPage(),querycar.getLimit());
        LambdaQueryChainWrapper<Car> wrapper=new LambdaQueryChainWrapper<>(carMapper);

        if(querycar.getStatus()!=null&&!querycar.getStatus().equals("")){
            wrapper.eq(Car::getStatus,querycar.getStatus());
        }else if(querycar.getSeriesId()!=null){
            wrapper.eq(Car::getSeriesId,querycar.getSeriesId());
        }else if(querycar.getBrandId()!=null){
            List<Integer> ids = seriesService.querySeriesByBrandId(querycar.getBrandId())
                    .stream().map(Series::getSeriesId).collect(Collectors.toList());
            wrapper.in(Car::getSeriesId,ids);
        }

        IPage<Car> carIPage = wrapper.page(page);

        // 转换为DTO并返回
        return carIPage.convert(this::getCarDTO);
    }
    private carDTO getCarDTO(Car one){
        carDTO carDTO = JSON.parseObject(JSON.toJSONString(one), carDTO.class);
        carDTO.setType(one.getCarType());
        Series series = seriesService.getById(one.getSeriesId());
        String brandName = brandService.getById(series.getBrandId()).getBrandName();
        carDTO.setSeriesName(series.getSeriesName());
        carDTO.setBrandName(brandName);
        return carDTO;
    }
}
